package cn.wanho.service.Impl;

import cn.wanho.dto.*;
import cn.wanho.mapper.*;
import cn.wanho.rvo.*;
import cn.wanho.rvo.ResultEnum;
import cn.wanho.service.exam.TeacherService;
import cn.wanho.util.*;
import com.alibaba.excel.EasyExcel;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Resource
    private ExamUserRolesMapper examUserRolesMapper;

    @Resource
    private ExamClassMapper examClassMapper;

    @Resource
    private ExamStageMapper examStageMapper;

    @Resource
    private ExamClassStageMapper examClassStageMapper;

    @Resource
    private ExamSummaryMapper examSummaryMapper;

    @Resource
    private ExamChooseSubjectMapper examChooseSubjectMapper;

    @Resource
    private ExamBlanksSubjectMapper examBlanksSubjectMapper;

    @Resource
    private ExamTfSubjectMapper examTfSubjectMapper;

    @Resource
    private ExamBigSubjectMapper examBigSubjectMapper;

    @Resource
    private ExamPaperSubjectMapper examPaperSubjectMapper;

    @Resource
    private ExamPaperMapper examPaperMapper;

    @Resource
    private ExamUserMapper examUserMapper;


    @Override
    public ResultVO updateStudentScore(Long subjectId, Integer score, Integer studentId, Integer userId) {
        int i = examSummaryMapper.updateSubjectGrade(studentId,subjectId,score);
        if(i > 0){
            return ResultVO.success(ResultEnum.UPDATE_STUDENT_SCORE_SUCCESS.getResCode(), ResultEnum.UPDATE_STUDENT_SCORE_SUCCESS.getResMsg());
        }
        else{
            return ResultVO.faiure(ResultEnum.UPDATE_STUDENT_SCORE_FAILURE.getResCode(),ResultEnum.UPDATE_STUDENT_SCORE_FAILURE.getResMsg());
        }
    }

    @Override
    public ResultVO queryAllStudent(Integer userId) {
        List<StudentVO> list = examSummaryMapper.selectAllStudent(userId);
        if(!list.isEmpty()){
            return ResultVO.success(ResultEnum.QUERY_STUDENT_SUCCESS.getResCode(), ResultEnum.QUERY_STUDENT_SUCCESS.getResMsg(),list);
        }else{
            return ResultVO.faiure(ResultEnum.QUERY_STUDENT_FAILURE.getResCode(), ResultEnum.QUERY_STUDENT_FAILURE.getResMsg());
        }
    }

    @Override
    @SneakyThrows
    public ResultVO queryRecentClass(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        int i = examUserRolesMapper.selectByUserId(userId);
        if (i == 3) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currentTime = dateFormat.parse(dateFormat.format(new Date()));
            List<ClassRVO> classRVOS = examClassMapper.selectClass(userId);
            List<ClassStageRVO> list = new ArrayList<>();
            for (ClassRVO classRVO : classRVOS) {
                Date endTime = classRVO.getEndTime();
                long diff =endTime.getTime() -currentTime.getTime();
                Long day = diff / (1000 * 60 * 60 * 24);
                ClassStageRVO classStageRVO = new ClassStageRVO(classRVO.getClassName(),classRVO.getStageName(),day);
                list.add(classStageRVO);
            }

            return ResultVO.success(ResultEnum.SELECT_CLASS_SUCCESS.getResCode(), ResultEnum.SELECT_CLASS_SUCCESS.getResMsg(),list);
        }else {
            return ResultVO.faiure(ResultEnum.NO_ROLES.getResCode(), ResultEnum.NO_ROLES.getResMsg());
        }
    }

    @Override
    @SneakyThrows
    public ResultVO createPaper(String paperName,String startTime,String endTime,MultipartFile file, HttpServletRequest request){
        Integer userId = (Integer) request.getAttribute("userId");
        int i = examUserRolesMapper.selectByUserId(userId);
        if (i == 3) {
            List<TemplatePaperEntity> entities = getTemplateEntities(file);
            System.out.println(entities);

            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = dateFormat.parse(startTime);
            Date date2 = dateFormat.parse(endTime);
            ExamPaper examPaper = new ExamPaper(paperName,date1,date2);
            examPaperMapper.insert(examPaper);
            Integer paperId = examPaper.getId();



            for (TemplatePaperEntity entity : entities) {
                ExamChooseSubject examChooseSubject=new ExamChooseSubject(entity.getChooseContent(),entity.getChooseAnswer(),entity.getIsAlone(),entity.getChooseScore());
                ExamBlanksSubject examBlanksSubject = new ExamBlanksSubject(entity.getBlanksContent(),entity.getBlanksAnswer(),entity.getBlanksScore());
                ExamTfSubject examTfSubject = new ExamTfSubject(entity.getTfContent(),entity.getTfAnswer(),entity.getTfScore());
                ExamBigSubject examBigSubject = new ExamBigSubject(entity.getBigContent(),entity.getBigAnswer(),entity.getBigScore());
                //把excel表的数据分别插入到四个题目表中
                examChooseSubjectMapper.insert(examChooseSubject);
                examBlanksSubjectMapper.insert(examBlanksSubject);
                examTfSubjectMapper.insert(examTfSubject);
                examBigSubjectMapper.insert(examBigSubject);

                Long chooseId = examChooseSubject.getId();
                Long blanksId = examBlanksSubject.getId();
                Long tfId = examTfSubject.getId();
                Long bigId = examBigSubject.getId();

                examPaperSubjectMapper.insert(paperId,chooseId,null,null,null);
                examPaperSubjectMapper.insert(paperId,null,blanksId,null,null);
                examPaperSubjectMapper.insert(paperId,null,null,tfId,null);
                examPaperSubjectMapper.insert(paperId,null,null,null,bigId);
            }

            return ResultVO.success(ResultEnum.CREATE_PAPER_SUCCESS.getResCode(), ResultEnum.CREATE_PAPER_SUCCESS.getResMsg());

        }else {
            return ResultVO.faiure(ResultEnum.NO_ROLES.getResCode(), ResultEnum.NO_ROLES.getResMsg());
        }
    }

    @Override
    public ResultVO passTeacher(Integer id,Integer tId) {
        System.out.println(tId);
        Integer role = examUserMapper.selectRole(id);
        System.out.println(role);
        if (role == 1 || role == 2){
            Integer role1 = examUserMapper.selectRole(tId);
            System.out.println(role1);
            if (role1 == 3){
                Integer i1 = examUserMapper.passTeacher(tId);
                if (i1 == 1){
                    return ResultVO.success(ResultEnum.UPDATE_TEACHER_SUCCESS.getResCode(),ResultEnum.UPDATE_TEACHER_SUCCESS.getResMsg());
                }else {
                    return ResultVO.faiure(ResultEnum.UPDATE_TEACHER_FAILURE1.getResCode(), ResultEnum.UPDATE_TEACHER_FAILURE1.getResMsg());
                }
            }else {
                return ResultVO.faiure(ResultEnum.UPDATE_TEACHER_FAILURE2.getResCode(), ResultEnum.UPDATE_TEACHER_FAILURE2.getResMsg());
            }
        }else{
            return ResultVO.faiure(ResultEnum.NO_MATCH_INFORMATION.getResCode(), ResultEnum.NO_MATCH_INFORMATION.getResMsg());
        }
    }

    @Override
    public ResultVO queryAllTeacher(Integer id) {
        Integer role = examUserMapper.selectRole(id);
        if (role == 1 || role == 2){
            List<TeacherRVO> examUsers = examUserMapper.queryAllTeacher();
            if (examUsers.isEmpty()){
                return ResultVO.faiure(ResultEnum.CREATE_TEACHER_FAILURE.getResCode(), ResultEnum.CREATE_TEACHER_FAILURE.getResMsg());
            }else{
                HashMap<String, Object> map = new HashMap<>();
                map.put("教师信息",examUsers);
                return ResultVO.success(ResultEnum.CREATE_TEACHER_SUCCESS.getResCode(),ResultEnum.CREATE_TEACHER_SUCCESS.getResMsg(),map);
            }
        }
        else{
            return ResultVO.faiure(ResultEnum.NO_MATCH_INFORMATION.getResCode(), ResultEnum.NO_MATCH_INFORMATION.getResMsg());
        }
    }

    private List<TemplatePaperEntity> getTemplateEntities(MultipartFile file) throws IOException {
        //定义的listener
        TemplatePaperListener listener = new TemplatePaperListener();
        EasyExcel.read(file.getInputStream(), TemplatePaperEntity.class, listener).sheet().doRead();
        //返回所有数据
        return listener.getData();
    }

    @Override
    @SneakyThrows
    public ResultVO uploadScore(Long subjectId, Integer studentId, Integer score, HttpServletRequest request)  {
        Integer userId = (Integer) request.getAttribute("userId");
        int flag = examUserRolesMapper.selectByUserId(userId);
        if (flag == 3) {
            int i = examSummaryMapper.uploadScore(subjectId, studentId, score);
            if (i > 0) {
                return ResultVO.success(ResultEnum.UPDATE_BIG_SUCCESS.getResCode(), ResultEnum.UPDATE_BIG_SUCCESS.getResMsg());
            }else {
                return ResultVO.faiure(ResultEnum.UPDATE_BIG_FAILURE.getResCode(), ResultEnum.UPDATE_BIG_FAILURE.getResMsg());
            }
        }else {
            return ResultVO.faiure(ResultEnum.NO_ROLES.getResCode(), ResultEnum.NO_ROLES.getResMsg());
        }
    }

    @Override
    @SneakyThrows
    public ResultVO queryPaperAnswer(Integer studentId, HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("userId");
        int flag = examUserRolesMapper.selectByUserId(userId);
        if (flag == 3) {
            List<PaperRVO> paperRVOS = examSummaryMapper.queryPaperAnswer(studentId);
            return ResultVO.success(ResultEnum.QUERY_PAPER_SUCCESS.getResCode(), ResultEnum.QUERY_PAPER_SUCCESS.getResMsg(),paperRVOS);
        }else {
            return ResultVO.faiure(ResultEnum.NO_ROLES.getResCode(), ResultEnum.NO_ROLES.getResMsg());
        }
    }
}
